/**
 * 使函数只执行一次，暂时用来模拟componentWillMount钩子
 *
 * @export
 * @param {function} fn
 * @return {function} 
 */
export function once(fn, cnt) {
    let count = cnt || 1;
    return function (...args) {
        if (count > 0) {
            --count;
            return fn(...args);
        }
    }
}

export function after(fn, cnt) {
    let count = cnt || 0;
    return function (...args) {
        if (count > 0) {
            --count;
        } else {
            return fn(...args);
        }
    }
}

export function between(fn, min, max) {
    let count = 0;
    return function (...args) {
        if (count < min) {
            ++count;
        } else if (count >= min && count < max) {
            ++count;
            return fn(...args);
        }
    }
}

const week = ['日', '一', '二', '三', '四', '五', '六'];

export function getTimeString() {
    const date = new Date();

    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, 0)}-${date.getDate().toString().padStart(2, 0)} 星期${week[date.getDay()]} ${date.getHours().toString().padStart(2, 0)}:${date.getMinutes().toString().padStart(2, 0)}:${date.getSeconds().toString().padStart(2, 0)}`
}

export function timeFormat(timeStamp, format) {
    if (!timeStamp) return null;
    
    const time = new Date(timeStamp);
    const date = {
        'M+': time.getMonth() + 1,
        'd+': time.getDate(),
        'h+': time.getHours(),
        'm+': time.getMinutes(),
        's+': time.getSeconds(),
        'q+': Math.floor((time.getMonth() + 3) / 3),
        'S+': time.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const k in date) {
        if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1
                ? date[k] : ('00' + date[k]).substr(('' + date[k]).length));
        }
    }
    return format;
}